var events = require('events');
process.mixin(GLOBAL, require('sys'), require('./tools'));

/**
 * Function that builds a function for the next component in the pipeline
 */
var next = function(scope, fns, pos) {
  return function() {
    if(pos <= (fns.length-1)) { //We have more components to send this on too
      var args = Array.prototype.slice.call(arguments);
      var cb = next(scope, fns, pos+1);
      args.push(cb);

      var ret = fns[pos].apply(scope, args);
      if(ret) {
        cb(ret);
      }
    } else {
      scope.emit('complete');
    }
  };
};

/**
 * Constructor for a Pipeline object
 */
var Pipeline = exports.Pipeline = function(components) {
  events.EventEmitter.call(this);
  var self = this;
  this.components = components;


  this.start = function() {
    next(this, self.components, 0).apply(this, arguments);
  };
}; 
process.inherits(Pipeline, events.EventEmitter);

